<template>
	<view class="comments-section">
		<!-- 评论标题 -->
		<view class="comments-header">
			<text class="comments-title">评论 {{comments.length}}</text>
			<!-- <view class="sort-options">
				<text class="sort-option" :class="{active: sortType === 'hot'}" @click="changeSort('hot')">最热</text>
				<text class="sort-option" :class="{active: sortType === 'new'}" @click="changeSort('new')">最新</text>
			</view> -->
		</view>

		<!-- 评论列表 -->
		<view class="comments-list">
			<view v-for="(comment, index) in comments" :key="comment.id" class="comment-item">
				<image class="avatar" :src="comment.avatar" mode="aspectFill"></image>
				<view class="comment-content">
					<view class="user-info">
						<text class="username">{{comment.username}}</text>
						<text class="create-time">{{comment.createTime}}</text>
					</view>
					<view class="comment-text">{{comment.content}}</view>

					<!-- 图片或视频 -->
					<!-- 					<view class="comment-media" v-if="comment.images && comment.images.length > 0">
						<image v-for="(img, imgIndex) in comment.images" :key="imgIndex" :src="img" mode="aspectFill"
							class="comment-image" @click="previewImage(comment.images, imgIndex)"></image>
					</view> -->

					<!-- 回复区域 -->
					<view class="reply-preview" v-if="comment.replies && comment.replies.length > 0">
						<view v-for="(reply, replyIndex) in comment.showAllReplies ? comment.replies : comment.replies.slice(0, 2)"
							:key="reply.id" class="reply-item">
							<text class="reply-username">{{reply.username}}：</text>
							<text class="reply-content">{{reply.content}}</text>
						</view>
						<view class="view-all-replies" v-if="comment.replyCount > 2 && !comment.showAllReplies"
							@click="toggleAllReplies(comment)">
							查看全部{{comment.replyCount}}条回复
						</view>
						<view class="collapse-replies" v-if="comment.showAllReplies" @click="toggleAllReplies(comment)">
							收起回复
						</view>
					</view>

					<!-- 操作栏 -->
					<view class="comment-actions">
						<view class="action-item" @click="showReplyInput(comment)">
							<u-icon size="24" name="chat"></u-icon>
							<text class="action-count">{{comment.replyCount}}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view class="load-more" v-if="loading">
				<text>加载中...</text>
			</view>
			<view class="no-more" v-if="noMore && comments.length > 0">
				<text>没有更多评论了</text>
			</view>
			<view class="no-comments" v-if="comments.length === 0 && !loading">
				<text>还没有评论，快来抢沙发吧~</text>
			</view>
		</view>

		<!-- 底部输入框 -->
		<view class="comment-input-container">
			<input class="comment-input" v-model="inputContent" :placeholder="inputPlaceholder" :focus="isInputFocus"
				@focus="onInputFocus" @blur="onInputBlur" />
			<view class="send-btn" :class="{active: inputContent.trim().length > 0}" @click="sendComment">
				发送
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			postId: {
				type: [String, Number],
				required: true
			},
			initialComments: {
				type: Array,
				default: () => []
			}
		},
		data() {
			return {
				comments: [],
				inputContent: '',
				isInputFocus: false,
				loading: false,
				noMore: false,
				page: 1,
				pageSize: 10,
				sortType: 'hot', // 'hot' or 'new'
				replyingTo: null // 当前正在回复的评论
			}
		},
		computed: {
			inputPlaceholder() {
				return this.replyingTo ? `回复@${this.replyingTo.username}` : '说点什么...'
			}
		},
		created() {
			// 初始化时给每条评论添加showAllReplies属性
			this.comments = this.initialComments.map(comment => ({
				...comment,
				showAllReplies: false
			}))

			// 如果没有初始数据，可以在这里加载第一页
			if (this.comments.length === 0) {
				this.loadComments()
			}
		},
		methods: {
			// 加载评论
			async loadComments() {
				if (this.loading || this.noMore) return

				this.loading = true

				try {
					// 这里替换为实际的API调用
					// const res = await this.$api.getComments({
					//   postId: this.postId,
					//   page: this.page,
					//   pageSize: this.pageSize,
					//   sort: this.sortType
					// })

					// 模拟API返回
					const mockComments = this.getMockComments(this.page, this.pageSize).map(comment => ({
						...comment,
						showAllReplies: false
					}))

					if (this.page === 1) {
						this.comments = mockComments
					} else {
						this.comments = [...this.comments, ...mockComments]
					}

					if (mockComments.length < this.pageSize) {
						this.noMore = true
					} else {
						this.page++
					}
				} catch (error) {
					console.error('加载评论失败', error)
					uni.showToast({
						title: '加载评论失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			// 切换显示全部回复/收起回复
			toggleAllReplies(comment) {
				const index = this.comments.findIndex(c => c.id === comment.id)
				if (index !== -1) {
					const updatedComment = {
						...comment,
						showAllReplies: !comment.showAllReplies
					}
					this.$set(this.comments, index, updatedComment)

					// 如果展开回复，滚动到该评论位置
					if (updatedComment.showAllReplies) {
						this.$nextTick(() => {
							const query = uni.createSelectorQuery().in(this)
							query.select(`.comment-item[data-id="${comment.id}"]`).boundingClientRect()
							query.exec(res => {
								if (res[0]) {
									uni.pageScrollTo({
										scrollTop: res[0].top - 20,
										duration: 300
									})
								}
							})
						})
					}
				}
			},

			// 其他方法保持不变...
			// changeSort, toggleLike, showReplyInput, sendComment, previewImage 等方法保持不变
			// ...
			// 加载评论
			async loadComments() {
				if (this.loading || this.noMore) return

				this.loading = true

				try {
					// 这里替换为实际的API调用
					// const res = await this.$api.getComments({
					//   postId: this.postId,
					//   page: this.page,
					//   pageSize: this.pageSize,
					//   sort: this.sortType
					// })

					// 模拟API返回
					const mockComments = this.getMockComments(this.page, this.pageSize)

					if (this.page === 1) {
						this.comments = mockComments
					} else {
						this.comments = [...this.comments, ...mockComments]
					}

					if (mockComments.length < this.pageSize) {
						this.noMore = true
					} else {
						this.page++
					}
				} catch (error) {
					console.error('加载评论失败', error)
					uni.showToast({
						title: '加载评论失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			// 切换排序方式
			changeSort(type) {
				if (this.sortType === type) return

				this.sortType = type
				this.page = 1
				this.noMore = false
				this.loadComments()
			},

			// 点赞/取消点赞
			async toggleLike(comment) {
				try {
					// 这里替换为实际的API调用
					// await this.$api.toggleLikeComment({
					//   commentId: comment.id,
					//   like: !comment.isLiked
					// })

					const index = this.comments.findIndex(c => c.id === comment.id)
					if (index !== -1) {
						const updatedComment = {
							...comment,
							isLiked: !comment.isLiked,
							likeCount: comment.isLiked ? comment.likeCount - 1 : comment.likeCount + 1
						}
						this.$set(this.comments, index, updatedComment)
					}
				} catch (error) {
					console.error('操作失败', error)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
				}
			},

			// 显示回复输入框
			showReplyInput(comment) {
				this.replyingTo = comment
				this.isInputFocus = true
			},

			// 发送评论
			async sendComment() {
				const content = this.inputContent.trim()
				if (!content) return

				try {
					// 这里替换为实际的API调用
					// const newComment = await this.$api.addComment({
					//   postId: this.postId,
					//   content,
					//   replyTo: this.replyingTo ? this.replyingTo.id : null
					// })

					// 模拟API返回
					const newComment = {
						id: Date.now(),
						avatar: '/static/default-avatar.png',
						username: '当前用户',
						createTime: '刚刚',
						content: content,
						isLiked: false,
						likeCount: 0,
						replyCount: 0,
						replies: [],
						images: []
					}

					if (this.replyingTo) {
						// 如果是回复
						const parentIndex = this.comments.findIndex(c => c.id === this.replyingTo.id)
						if (parentIndex !== -1) {
							const parentComment = this.comments[parentIndex]
							const newReply = {
								id: Date.now() + 1,
								username: '当前用户',
								content: content.replace(`@${parentComment.username}`, '').trim(),
								createTime: '刚刚'
							}

							const updatedParent = {
								...parentComment,
								replies: [...(parentComment.replies || []), newReply],
								replyCount: parentComment.replyCount + 1
							}

							this.$set(this.comments, parentIndex, updatedParent)
						}
					} else {
						// 如果是新评论
						this.comments.unshift(newComment)
					}

					this.inputContent = ''
					this.replyingTo = null
					this.isInputFocus = false

					uni.pageScrollTo({
						scrollTop: 0,
						duration: 300
					})
				} catch (error) {
					console.error('发送评论失败', error)
					uni.showToast({
						title: '发送评论失败',
						icon: 'none'
					})
				}
			},

			// 查看全部回复
			viewAllReplies(comment) {
				uni.navigateTo({
					url: `/pages/comment/replyDetail?commentId=${comment.id}&postId=${this.postId}`
				})
			},

			// 预览图片
			previewImage(images, currentIndex) {
				uni.previewImage({
					current: currentIndex,
					urls: images
				})
			},

			onInputFocus() {
				// 可以在这里处理键盘弹起时的布局调整
			},

			onInputBlur() {
				// 可以在这里处理键盘收起时的布局调整
			},

			// 模拟获取评论数据
			getMockComments(page, pageSize) {
				const mockComments = []
				const start = (page - 1) * pageSize + 1

				for (let i = start; i < start + pageSize; i++) {
					mockComments.push({
						id: Date.now() + i,
						avatar: `http://gips1.baidu.com/it/u=8355271,1357180122&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960`,
						username: `用户${i}`,
						createTime: `${i}分钟前`,
						content: `这是第${i}条评论的内容，模拟小红书风格的评论展示效果`,
						isLiked: i % 4 === 0,
						likeCount: Math.floor(Math.random() * 100),
						replyCount: i % 3 === 0 ? 5 : 0, // 增加回复数量方便测试
						replies: i % 3 === 0 ? [{
								id: Date.now() + i + 1000,
								username: `回复用户${i}`,
								content: '这是第一条回复内容',
								createTime: '1分钟前'
							},
							{
								id: Date.now() + i + 2000,
								username: `回复用户${i + 1}`,
								content: '这是第二条回复内容',
								createTime: '2分钟前'
							},
							{
								id: Date.now() + i + 3000,
								username: `回复用户${i + 2}`,
								content: '这是第三条回复内容',
								createTime: '3分钟前'
							},
							{
								id: Date.now() + i + 4000,
								username: `回复用户${i + 3}`,
								content: '这是第四条回复内容',
								createTime: '4分钟前'
							},
							{
								id: Date.now() + i + 5000,
								username: `回复用户${i + 4}`,
								content: '这是第五条回复内容',
								createTime: '5分钟前'
							}
						] : [],
						images: i % 5 === 0 ? [
							'http://gips1.baidu.com/it/u=8355271,1357180122&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960',
							'http://gips0.baidu.com/it/u=2254920273,941506475&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960'
						] : []
					})
				}

				return mockComments
			}
		}
	}
</script>

<style scoped>
	/* 原有样式保持不变... */
	.comments-section {
		padding: 32rpx 0;
		background-color: #fff;
	}

	.comments-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.comments-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.sort-options {
		display: flex;
	}

	.sort-option {
		font-size: 26rpx;
		color: #999;
		margin-left: 32rpx;
		position: relative;
	}

	.sort-option.active {
		color: #ff2442;
	}

	.sort-option.active::after {
		content: '';
		position: absolute;
		bottom: -8rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 40rpx;
		height: 4rpx;
		background-color: #ff2442;
		border-radius: 2rpx;
	}

	.comments-list {
		margin-bottom: 120rpx;
	}

	.comment-item {
		display: flex;
		padding: 24rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.avatar {
		width: 64rpx;
		height: 64rpx;
		border-radius: 50%;
		margin-right: 16rpx;
		flex-shrink: 0;
	}

	.comment-content {
		flex: 1;
	}

	.user-info {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.username {
		font-size: 28rpx;
		color: #333;
		margin-right: 16rpx;
	}

	.create-time {
		font-size: 24rpx;
		color: #999;
	}

	.comment-text {
		font-size: 28rpx;
		color: #333;
		line-height: 1.5;
		margin-bottom: 20rpx;
	}

	.comment-media {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 16rpx;
	}

	.comment-image {
		width: 200rpx;
		height: 200rpx;
		border-radius: 8rpx;
		margin-right: 16rpx;
		margin-bottom: 16rpx;
		background-color: #f5f5f5;
	}

	.reply-preview {
		background-color: #f7f7f7;
		border-radius: 8rpx;
		padding: 16rpx;
		margin-bottom: 16rpx;
	}

	.reply-item {
		font-size: 26rpx;
		color: #333;
		line-height: 1.5;
		margin-bottom: 8rpx;
	}

	.reply-username {
		color: #576b95;
	}

	.view-all-replies {
		font-size: 24rpx;
		color: #999;
		margin-top: 8rpx;
	}

	.comment-actions {
		display: flex;
		align-items: center;
	}

	.action-item {
		display: flex;
		align-items: center;
		margin-right: 32rpx;
		color: #999;
	}

	.action-item .iconfont {
		font-size: 32rpx;
		margin-right: 8rpx;
	}

	.action-item .icon-like-fill.liked {
		color: #ff2442;
	}

	.action-count {
		font-size: 24rpx;
	}

	.load-more,
	.no-more,
	.no-comments {
		text-align: center;
		padding: 32rpx;
		font-size: 26rpx;
		color: #999;
	}

	.comment-input-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		padding: 16rpx 32rpx;
		background-color: #fff;
		border-top: 1rpx solid #f5f5f5;
		z-index: 100;
		padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
	}

	.comment-input {
		flex: 1;
		height: 72rpx;
		background-color: #f7f7f7;
		border-radius: 36rpx;
		padding: 0 24rpx;
		font-size: 28rpx;
		margin-right: 16rpx;
	}

	.send-btn {
		font-size: 28rpx;
		color: #ccc;
		padding: 0 24rpx;
	}

	.send-btn.active {
		color: #ff2442;
	}

	/* 新增或修改的样式 */
	.reply-item {
		font-size: 26rpx;
		color: #333;
		line-height: 1.5;
		margin-bottom: 8rpx;
		padding: 8rpx 0;
	}

	.view-all-replies,
	.collapse-replies {
		font-size: 24rpx;
		color: #999;
		margin-top: 8rpx;
		padding: 8rpx 0;
	}

	.view-all-replies:active,
	.collapse-replies:active {
		background-color: #f5f5f5;
		border-radius: 4rpx;
	}
</style>